from rest_framework import status, mixins
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from .services import OrderService
from .serializers import OrderSerializer, CreateOrderSerializer, ReviewSerializer
from accounts.models import Technician


class OrderViewSet(mixins.ListModelMixin,
                   mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   GenericViewSet):
    """订单视图集"""
    permission_classes = [IsAuthenticated]
    serializer_class = OrderSerializer
    
    def get_queryset(self):
        """根据用户角色返回不同的订单查询集"""
        try:
            return OrderService.get_orders_for_user(self.request.user)
        except PermissionError:
            return []
    
    def get_serializer_class(self):
        """根据操作返回不同的序列化器"""
        if self.action == 'create':
            return CreateOrderSerializer
        return OrderSerializer
    
    def list(self, request, *args, **kwargs):
        """获取订单列表"""
        try:
            orders_data = OrderService.get_orders_for_user(request.user)
            return Response(orders_data)
        except PermissionError as e:
            return Response({'error': str(e)}, status=status.HTTP_403_FORBIDDEN)
    
    def create(self, request, *args, **kwargs):
        """创建订单"""
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            try:
                order_data = OrderService.create_order(serializer.validated_data, request.user)
                return Response(order_data, status=status.HTTP_201_CREATED)
            except PermissionError as e:
                return Response({'error': str(e)}, status=status.HTTP_403_FORBIDDEN)
            except Exception as e:
                return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    def retrieve(self, request, *args, **kwargs):
        """获取订单详情"""
        order_id = kwargs.get('pk')
        try:
            order_data = OrderService.get_order_detail(order_id, request.user)
            return Response(order_data)
        except ValueError as e:
            return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND)
        except PermissionError as e:
            return Response({'error': str(e)}, status=status.HTTP_403_FORBIDDEN)


class OrderActionViewSet(GenericViewSet):
    """订单操作视图集"""
    permission_classes = [IsAuthenticated]
    
    def accept(self, request, pk=None):
        """技师接单"""
        try:
            order_data = OrderService.accept_order(pk, request.user)
            return Response(order_data)
        except ValueError as e:
            return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND)
        except PermissionError as e:
            return Response({'error': str(e)}, status=status.HTTP_403_FORBIDDEN)
    
    def cancel(self, request, pk=None):
        """取消订单"""
        try:
            order_data = OrderService.cancel_order(pk, request.user)
            return Response(order_data)
        except ValueError as e:
            return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND)
        except PermissionError as e:
            return Response({'error': str(e)}, status=status.HTTP_403_FORBIDDEN)
    
    def complete(self, request, pk=None):
        """完成订单"""
        try:
            order_data = OrderService.complete_order(pk, request.user)
            return Response(order_data)
        except ValueError as e:
            return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND)
        except PermissionError as e:
            return Response({'error': str(e)}, status=status.HTTP_403_FORBIDDEN)


class ReviewViewSet(mixins.CreateModelMixin, GenericViewSet):
    """评价视图集"""
    permission_classes = [IsAuthenticated]
    serializer_class = ReviewSerializer
    
    def create(self, request, *args, **kwargs):
        """添加评价"""
        order_id = kwargs.get('order_id')
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            try:
                review_data = OrderService.add_review(order_id, serializer.validated_data, request.user)
                return Response(review_data, status=status.HTTP_201_CREATED)
            except ValueError as e:
                return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND)
            except PermissionError as e:
                return Response({'error': str(e)}, status=status.HTTP_403_FORBIDDEN)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)